import { snakeCase } from 'lodash'
import store from '@/store'

// 动态直接引入
export const joinView = filePath => require('@/views' + filePath + '.vue').default
// 动态懒加载
export const joinViewLazy = filePath => () => import('@/views' + filePath + '.vue')

/**
 * 列表转为树形列表
 * @param {列表} list
 * @param {菜单根id} rootId
 * @returns 树形
 */
export const listToTree = (list, { pidName = 'pid', idName = 'id' }, rootId = '0') => {
  list.forEach(child => {
    const pid = child[pidName]
    if (pid !== rootId) {
      list.forEach(parent => {
        if (parent[idName] === pid) {
          parent.children = parent.children || []
          parent.children.push(child)
        }
      })
    }
  })
  return list.filter(n => n[pidName] === rootId)
}

export const getMainRoute = async (params = {}) => {
  // 未来可定义静态路由
  const mainChildren = []
  const mainRoute = {
    path: '/',
    name: 'main',
    component: joinView('/Main'),
    children: mainChildren
  }

  let menuList = await store.dispatch('Menus/getMenuListAll', params)
  if (!menuList.length) {
    return mainRoute
  }

  menuList = menuList.filter(menu => menu.url)
  const routeList = menuList.map(item => ({
    menuId: item.menuId,
    parentId: item.parentId,
    path: item.url,
    name: snakeCase(item.url),
    component: joinView(item.pageUrl || '/About'),
    meta: {
      type: item.type,
      title: item.name || '',
      key: item.key || '',
      icon: item.icon || '',
      orderNum: item.orderNum || 0
    }
  }))
  mainRoute.children = [...routeList, ...mainRoute.children]
  return mainRoute
}

/**
 * 获取uuid
 */
export const getUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}
